﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Course.Models;
using Course.Views;
using System.Windows.Forms;
namespace Course.Controllers
{
    public class StuHomeController
    {
        public User Stu { get; set; }
        public StuHome View;
        public StuHomeModel Model;
        public DataClasseDataContext context = new DataClasseDataContext();
        public StuHomeController(StuHome view,string id) {
            Stu = context.User.SingleOrDefault(u=>u.UserId==id);            
            Model = new StuHomeModel();
            this.View = view;
            this.View.Controller = this;
            Model.UserId = Stu.UserId;
            Model.UserName = Stu.UserName;
            Model.Grade = Stu.Grade.ToString();
            Model.Class = Stu.Class.ToString();
			//this.View.dataGridView1.
            //View.dataGridView1.DataSource=context.Course.Where(c => c.Status == 1).ToList();
        }

        public bool SaveChanges()
        {
            User temp = context.User.SingleOrDefault(u => u.UserId == Stu.UserId);
            if (temp != null)
            {
                temp.Class = Model.eClass;
                temp.Grade = Model.eGrade;
                context.SubmitChanges();
                return true;
            }
            else {
                return false;
            }
			
        }
        public void  searchCourse()
        {
  
            List<CourseView> list = context.CourseView.Where(u=>u.UserName==Model.SearchValue).ToList<CourseView>();
            if (list == null)
            {
                MessageBox.Show("list is null");
                list = new List<CourseView>();
            }
            MessageBox.Show("size:"+list.Count);
            CourseView course = context.CourseView.SingleOrDefault(c => c.CourseName.Contains( Model.SearchValue));
            if (course != null)
            {
                list.Add(course);
          
      
            }
            View.dataGridView1.DataSource = list;
   
        }
        public bool selectCourse() {
            if (Model.CourseId == null) return false; //no input
            Course course = context.Course.SingleOrDefault(c=>c.CourseId==int.Parse(Model.CourseId));
            if (course == null||course.Capicity<=0) return false; // class full
			if(context.Select.SingleOrDefault(s=>s.StuId==Stu.UserId&&s.CourseId==course.CourseId)!=null) return false; //have selected this class
            Select select = new Select();
            select.CourseId = course.CourseId;
            select.StuId = Stu.UserId;
            course.Capicity -= 1;
            context.Select.InsertOnSubmit(select);
            context.SubmitChanges();
            return true;
        }
    }
}
